import cheerio from 'cheerio'
import iconv from 'iconv-lite'
import got from 'got'
import { restoreId } from '../utils'
import { ICategory } from '../typings'

let covers = new Map<string, string>()

let http = got.extend({
  prefixUrl: process.env.targetUrl,
  timeout: 1000 * 30,
  hooks: {
    beforeRequest: [
      options => {
        options.headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
        options.headers['Referer'] = process.env.targetUrl
      }
    ]
  }
})

async function getHtmlDoc(partUrl: string) {
  let { rawBody } = await http.get(partUrl)
  let html = iconv.decode(rawBody, 'gb2312').toString()
  return cheerio.load(html)
}

const dataService = {
  getIndexDoc: async () => {
    return await getHtmlDoc(`index.html`)
  },
  getDetailDoc: async (id: string) => {
    return await getHtmlDoc(`html/${restoreId(id)}`)
  },
  getListDoc: async (category: ICategory, page: number) => {
    return await getHtmlDoc(`html/${category.path}/list_${category.id}_${page}.html`)
  },
  getCoverUrl: async (id: string) => {
    if (covers.has(id)) {
      return covers.get(id)!
    }
    let $ = await dataService.getDetailDoc(id)
    let src = $('#Zoom img').first().attr('src')
    if (src) {
      covers.set(id, src)
      return src
    }
  },
  getCategorys: () => {
    return process.env.categorys as unknown as ICategory[]
  },
  getCategoryByPath: (path: string) => {
    let items = dataService.getCategorys()
    for (const item of items) {
      if (item.path === path) {
        return { category: item }
      }
      if (item.children && item.children.length > 0) {
        let findRes = item.children.find(n => n.path === path)
        if (findRes) {
          return { category: findRes, parent: item }
        }
      }
    }
    return {}
  }
}

export { dataService }
